﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using System.Linq;
using System.Collections.Generic;
using TyMES.Model.BaseInformation;
using TyMES.ViewModel.BaseInformation.ProductVMs;
using TyMES.Model;
using static TyMES.BaseInformation.Controllers.StationController;
using TyMES.Communication;
using TyMES.Services;
using TyMES.Model.Record;

namespace TyMES.BaseInformation.Controllers
{
    [AuthorizeJwtWithCookie]
    [ActionDescription("_Model.Product")]
    [ApiController]
    [Route("/api/BaseInformation/Product")]
    public partial class ProductController : BaseApiController
    {
        private readonly PassStationService passStationService;

        public ProductController(PassStationService passStationService)
        {
            this.passStationService = passStationService;
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public IActionResult Get(string id)
        {
            var vm = Wtm.CreateVM<ProductVM>(id);
            return Ok(vm);
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("[action]")]
        public async Task<IActionResult> Create(ProductVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoAddAsync();
   
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("[action]")]
        public async Task<IActionResult> Edit(ProductVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoEditAsync(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }
                

        [HttpPost("BatchEdit")]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult BatchEdit(ProductBatchVM vm)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(vm.Ids.Count());
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<ProductBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<ProductImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(ProductImportVM vm)
        {

            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm.EntityList.Count);
            }
        }


        [HttpGet("GetProducts")]
        public ActionResult GetProducts()
        {
            return Ok(DC.Set<Product>().GetSelectListItems(Wtm, x => x.ProductVersion, x => x.ProductCode.ToString()));
        }

        public record ProductPara(string ProductVersion);
        [HttpPost("GetProductInfoByProductVersion")]
        public ActionResult GetProductInfoByProductVersion(ProductPara para)
        {
            var rv1 = DC.Set<Product>().Where(e => e.ProductVersion == para.ProductVersion).FirstOrDefault();
            return Ok(new { ProductName = rv1.ProductName , ProductCode = rv1.ProductCode});
        }


        public record JudgeProductGRPara(string CSSN);
        [HttpPost("JudgeProductGR")]
        public async Task<ActionResult> JudgeProductGR(JudgeProductGRPara para)
        {
            try
            {
                //var GetTZSN =await passStationService.SearchTZSN(para.CSSN);
                //if (!GetTZSN.Success)
                //    return Ok(new { Success = false, Mesg = GetTZSN.Mesg });
                if(para.CSSN.Substring(0,7)=="DM-TG-Y")
                    return Ok(new { Success = false, Mesg =$"{para.CSSN}是标准件SN" });
                var order = DC.Set<TrayBindVSN>().Where(x=>x.VSN==para.CSSN).FirstOrDefault()?.OrderCode;
                var productCode = DC.Set<Order_Model>().Where(x=>x.OrderCode==order).FirstOrDefault()?.MaterialCode;
                var rv1 = DC.Set<Product>().Where(e => e.ProductCode == productCode).FirstOrDefault();
                return Ok(new { Success = true, Mesg = rv1.ProductStatus });
            }
            catch (Exception ex)
            {
                return Ok(new { Success = false, Mesg = ex.Message });
            }
        }

    }
}